<!--
 * @Descripttion: 通行策略
 * @version:
 * @Author: wl
 * @Date: 2020-05-21 17:00:50
 * @LastEditors: wl
 * @LastEditTime: 2020-07-10 16:49:28
-->

<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="选择小区:">
            <el-select v-model="filters.CID" filterable placeholder="请选择" @change="search" clearable>
              <el-option
                v-for="item in getCommunity"
                :key="item.CID"
                :label="item.name"
                :value="item.CID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员名称">
            <el-input
              v-model="filters.name"
              placeholder="请输入"
              @keydown.enter.native="search"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="人员类型">
            <el-select v-model="filters.type" placeholder="请选择" @change="search" clearable>
              <el-option
                v-for="item in houseList"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据来源">
            <el-select v-model="filters.registration" filterable @change="search" placeholder="请选择" clearable>
              <el-option v-for="item in source" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button type="primary" @click="search">查询</el-button>
      </div>
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="currentSetingList"
          stripe
          border
          v-loading="loading"
          style="width: 100%"
          element-loading-text="加载中..."
        >
          <el-table-column prop="name" header-align="center" align="center" label="姓名">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">{{ scope.row.name }}</span>
              <span v-else>{{ scope.row.names }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gender" header-align="center" align="center" label="性别">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.gender == 0">男</span>
                <span v-if="scope.row.gender == 1">女</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号码"
            width="110"
            header-align="center"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.phone }}
              </span>
              <span v-else>{{ hideOfString(scope.row.phone) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="身份证" width="160" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.idCard }}
              </span>
              <span v-else>{{ hideOfString(scope.row.idCard) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="type" label="人员类型" width="100" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ typeToName(scope.row.type) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="regist"
            label="数据来源"
            width="100"
            header-align="center"
            align="center"
          ></el-table-column>
          <el-table-column prop="CID" label="所在小区" align="center" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ seachvill(scope.row.CID) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="人员地址" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.address ? scope.row.address : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="CType"
            header-align="center"
            width="250"
            align="center"
            label="通行类型"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="scope.row.current.length && scope.row.current[0].personType === 28">黑名单</span>

              <span v-else-if="scope.row.CType == 1">
                日期段:{{
                  $format(scope.row.current[0].dayTime[0] || new Date()) +
                  '-' +
                  $format(scope.row.current[0].dayTime[1] || new Date())
                }}
              </span>
              <span v-else-if="scope.row.CType == 2">
                时间段:{{
                  $format(scope.row.current[0].dayTime[0] || new Date()) +
                  '-' +
                  $format(scope.row.current[0].dayTime[1] || new Date())
                }}
              </span>
              <span v-else-if="scope.row.CType == 3">次数:{{ scope.row.count }}</span>
              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="400" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, handleEdit) : (isCheckEncryption = true)
                "
                v-show="hasPerm('pass:strategy:setup')"
              >
                添加
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click="
                  getCheckEncryption()
                    ? get_sensitive_fields(scope.row, handleEditImg)
                    : (isCheckEncryption = true)
                "
                v-show="hasPerm('pass:strategy:phono')"
              >
                查看照片
              </el-button>
              <el-button
                type="warning"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, checkPhoto) : (isCheckEncryption = true)
                "
                v-show="hasPerm('pass:strategy:details')"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 头像 -->
        <!-- 弹框 -->
        <el-dialog :visible.sync="dialogVisibleImg" :before-close="handleClose" width="30%">
          <img style="width: 100%" :src="getItemPhoto(currentImg)" class="imgDia" v-image-preview />
        </el-dialog>
      </div>
      <div slot="footer">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
    </page>
    <!-- 设置的弹窗 -->

    <el-dialog title="设置" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
      <el-form :model="form" label-width="80px" ref="form">
        <el-form-item label="设置">
          <el-radio-group v-model="form.personType" @change="change">
            <el-radio :label="27">白名单（永久通行）</el-radio>
            <el-radio :label="28">黑名单（禁止通行）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.personType == 27" label="通行类型">
          <el-radio v-model="form.CType" :label="1">
            <!-- <span>时间选择框：</span> -->
            <span class="demonstration">通行日期段</span>
            <el-date-picker
              v-if="form.CType == 1"
              v-model="form.dayTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-radio>
          <el-radio v-model="form.CType" :label="2">
            <span>通行时间段</span>
            <el-date-picker
              v-if="form.CType == 2"
              v-model="form.dayTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
            <el-time-select
              v-if="form.CType == 2"
              placeholder="开始时间"
              v-model="form.startTime"
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '24:00'
              }"
            ></el-time-select>
            <el-time-select
              v-if="form.CType == 2"
              placeholder="结束时间"
              v-model="form.endTime"
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '24:00',
                minTime: form.startTime
              }"
            ></el-time-select>
          </el-radio>
          <el-radio v-model="form.CType" :label="3">
            <span>通行的次数</span>
            <el-input
              v-if="form.CType == 3"
              onkeyup="this.value=this.value.replace(/[^\d]/g,'')"
              v-model="form.count"
              placeholder
            ></el-input>
          </el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="canaelSumbit">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="身份验证" :visible.sync="isCheckEncryption">
      <CheckEncryption @close="isCheckEncryption = false"></CheckEncryption>
    </el-dialog>
  </div>
</template>

<script>
import CheckEncryption from '@/components/CheckEncryption';
export default {
  components: {
    CheckEncryption
  },
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^^1[0-9]{10}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error('请输入合法的手机号'));
    };
    return {
      isCheckEncryption: false,
      // 小区列表
      villageList: [],
      currentImg: '',
      // 头像弹框
      dialogVisibleImg: false,
      asideShow: false,
      filters: {
        CID: '',
        name: '',
        registration: '',
        type: ''
      },
      pageRequest: {
        page: 1,
        limit: 10
      },
      loading: false,
      totalSize: 0,
      options: [
        {
          value: 0,
          label: '未推送'
        },
        {
          value: 1,
          label: '推送异常'
        },
        {
          value: 2,
          label: '推送成功'
        },
        {
          value: 3,
          label: '推送失败'
        }
      ],
      // 小区列表
      getCommunity: [],
      //  人员类型
      houseList: [],
      //  通行策略列表
      currentSetingList: [],
      // 操作的弹窗
      dialogVisible: false,
      //设置表单
      form: {
        auditPID: '',
        personType: '',
        count: 0,
        CType: '',
        dayTime: '', //时间段的日期
        startTime: '', //时间
        endTime: '',
        Idcard: '',
        photo: '',
        PID: '',
        phone: '',
        name: '',
        ctime: []
      },
      //   数据来源
      source: [],
      photoCheck: 0
    };
  },
  methods: {
    //查看
    checkPhoto(row) {
      if (row.photoCheck == this.photoCheck) {
        this.photoCheck = 0;
      } else {
        this.$nextTick(() => {
          //nextTick并不是用来监听DOM变更，它的作用是一次性更改数据，并且渲染DOM
          this.$set(this.currentSetingList, this.photoCheck - 1, row);
        });
        this.photoCheck = row.photoCheck;
      }
    },
    handleClose() {
      this.dialogVisibleImg = false;
    },
    // 查看头像
    handleEditImg: function (params) {
      if (params.photo) {
        this.currentImg = params.photo;
      }
      this.dialogVisibleImg = true;
    },
    search() {
      this.pageRequest.page = 1;
      this.handleQuery();
    },
    // 获取列表数据
    handleQuery(val) {
      this.loading = true;
      let params = {
        name: this.filters.name,
        type: this.filters.type,
        DID: this.filters.DID,
        CID: this.filters.CID,
        registration: this.filters.registration,
        page: val ? '' : this.pageRequest.page,
        limit: val ? '' : this.pageRequest.limit
      };
      this.$api.personPass
        .currentSeting(params)
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.currentSetingList = res.data;
            this.totalSize = res.count;
            this.currentSetingList.forEach((item, index) => {
              // item.photos = this.global.baseUrlImage + "avatar/" + item.photo;
              //  身份证加密
              item.names = this.formatName(item.name);
              item.photoCheck = index + 1;
              // 时间处理
              item.updateTime = this.$format(item.updateTime);
              this.source.forEach((val) => {
                if (val.DID == item.registration) {
                  item.regist = val.name;
                }
              });
              if (item.current) {
                item.current.forEach((val) => {
                  item.CType = val.CType;
                  item.count = val.count;
                });
              }
            });
          } else {
            this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
          }
        })
        .catch((err) => {
          this.$message({
            type: 'error',
            message: '请求超时' + err
          });
        });
    },
    //名字脱敏
    formatName(name) {
      var newStr;
      if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
      } else if (name.length > 2) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
          char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
      } else {
        newStr = name;
      }
      return newStr;
    },
    // 小区查询
    getCommunityList() {
      this.getCommunity = this.$store.state.village.villageList;
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = '';
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + 'avatar/' + id;
      return url;
    },
    // 查询小区
    seachvill(val) {
      for (let index = 0; index < this.getCommunity.length; index++) {
        const element = this.getCommunity[index];
        if (val == element.CID) {
          return element.name;
        }
      }
    },
    typeToName(type) {
      for (let index = 0; index < this.houseList.length; index++) {
        var item = this.houseList[index];
        if (type === item.DID) {
          return item.name;
        }
      }
      return '-';
    },
    // 设置界面
    handleEdit(row) {
      this.dialogVisible = true;
      this.form = Object.assign({}, row);
    },
    // 提交设置
    submitForm() {
      let timeArr = [];
      if (this.form.dayTime) {
        timeArr = this.form.dayTime;
      } else if (this.form.startTime || this.form.endTime) {
        timeArr.push(this.form.startTime, this.form.endTime);
      }

      this.form.count = parseInt(this.form.count);

      let params = {
        Idcard: this.form.idCard,
        personType: this.form.personType,
        time: timeArr
      };
      let parmm = Object.assign(params, this.form);
      console.log(params);

      let param = JSON.stringify(parmm);
      this.$api.personPass.setingAdd(param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '操作成功'
          });
          this.dialogVisible = false;
          this.$refs['form'].resetFields();
          this.handleQuery();
        } else {
          this.$message({
            type: 'danger',
            message: '添加失败'
          });
        }
      });
    },
    // 分页
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
    //x按钮
    closeDialog() {
      this.dialogVisible = false;
      this.$refs['form'].resetFields();
      this.active = false;
    },

    change(val) {
      if (val == 0) {
        this.active = true;
      } else if (val == 1) {
        this.active = false;
      }
    },
    // 取消按钮
    canaelSumbit() {
      this.dialogVisible = false;
      this.$refs['form'].resetFields();
      this.active = false;
    }
  },
  mounted() {
    this.filters.CID = localStorage.getItem('home_CID');
    this.handleQuery();
    this.getCommunityList();
    let dictList = JSON.parse(sessionStorage.getItem('dictData'));
    this.houseList = dictList.sys_person_type;
    this.source = dictList.sys_persion_source;
  }
};
</script>

<style lang='scss' scoped>
.el-radio {
  width: 70%;
  margin-top: 15px;
}
.el-input__inner {
  width: 35%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 35%;
}
</style>
